<template>
  <div :style="{ 'pointer-events': banClick === true ? 'none' : '' }">
    <Nav message="1" />
    <div style="border-top: 0.5rem rgb(115, 192, 243) solid"></div>

    <div v-for="(item, index) in cardDetail" :key="index">
      <div class="m-item">
        <!-- 复选框 -->
        <van-checkbox-group
          v-model="opt"
          ref="checkboxGroup"
          checked-color="rgb(255, 164, 45)"
          style="width: 7%; float: left; padding-left: 0.3rem"
          disabled:true
        >
          <van-checkbox
            :name="index"
            @click="optAmount(index)"
            style="height: 7rem"
          >
          </van-checkbox>
        </van-checkbox-group>

        <van-card
          :price="item.price"
          :title="item.spuName"
          :thumb="item.icon"
          style="width: 91.1%; float: right"
          @click="goItem(item.spuId)"
        >
          <template #title>
            <div class="van-multi-ellipsis--l3" style="font-size: 0.8rem">
              {{ item.spuName }}
            </div>
          </template>
          <template #tags>
            <van-tag
              v-for="tag in item.skuTag"
              :key="tag"
              style="margin-right: 0.3rem"
              >{{ tag }}</van-tag
            >
          </template>
        </van-card>

        <!-- 记录步进器所在的复选框index -->
        <div @click="stepperOfCheckbox(index)">
          <!-- 步进器 -->
          <van-stepper
            v-model="cardDetail[index].num"
            style="float: right"
            @change="stepper"
          />
        </div>

        <van-cell>
          <van-col style="float: right">配送：快递￥{{ item.freight }}</van-col>
        </van-cell>

        <van-cell style="font-weight: bold">
          <van-col style="color: rosybrown; float: right"
            >共{{ item.num }}件 小计：￥{{
              (item.amount = parseFloat(
                item.num * item.price + item.freight
              ).toFixed(2))
            }}
          </van-col>
        </van-cell>
      </div>
    </div>
    <div style="height: 4rem"></div>
    <van-submit-bar
      :price="this.cardAmount"
      button-text="结算"
      @submit="onSubmit"
    >
      <template #default>
        <van-button
          type="primary"
          @click="checkAll"
          style="
            background: rgb(255, 164, 45);
            border: none;
            color: #333;
            float: left;
          "
          ><b>全选</b></van-button
        >
        <van-button
          type="info"
          @click="deleteCard"
          style="
            background: rgb(255, 108, 120);
            border: none;
            color: #333;
            float: left;
          "
          ><b>删除</b></van-button
        >
      </template>
    </van-submit-bar>
  </div>
</template>
<script>
import Nav from "@/components/Nav.vue";
export default {
  components: {
    Nav,
  },
  created() {
    let isShopToken = this.$cookie.get("shoptoken");
    if (isShopToken == null) {
      this.$router.push({
        path: "/login",
        query: { item: this.$route.path },
      });
    }

    const _this = this;
    axios
      .get(this.$api + "card/list", {
        params: {
          token: isShopToken,
        },
      })
      .then(function (resp) {
        console.log("购物车list")
        console.log(resp)
        _this.cardDetail = resp.data.data.cardDetail;
      });
  },
  beforeUpdate() {
    // 展示所有选中商品
    if (this.beforeUpdateFlag) {
      for (let index = 0; index < this.cardDetail.length; index++) {
        if (this.cardDetail[index].isOpt != 1) {
          this.opt[index] = index;
        } else {
          this.opt[index] = -1;
        }
      }
      console.log("beforeUpdate()函数执行");
      console.log(this.opt);
      this.beforeUpdateFlag = false;
    }

    if (this.firstCardDetailFlag) {
      for (let index = 0; index < this.cardDetail.length; index++) {
        if (this.cardDetail[index].isOpt == 0) {
          console.log(this.cardAmount);
          this.cardAmount += this.cardDetail[index].amount;
        }
      }
      this.firstCardDetailFlag = false;
    }
  },
  data() {
    return {
      banClick: false,
      firstCardDetailFlag: true, //首次进入页面后，根据选中的复选框，计算总价格
      stepperOfCheckboxIndex: null, //步进器所在的复选框的index
      stepperCount: null, //步进器计数
      beforeUpdateFlag: true, //让beforeUpdate函数只在刷新页面时执行一次
      opt: [], //动态记录复选框的选中状态
      cardAmount: 0, //总价单位分
      cardDetail: [
        // {
        //   // isOpt: 1, //自己定义的
        //   // spuId: 10,
        //   skuId: 100,
        //   // orderId: "1586242977480760998",
        //   spuName:
        //     "Apple Mac Pro Desktop Computer, 3.5GHz 8-Core Intel Xeon W, 32GB Memory, 256GB SSD, Radeon Pro 580X 8GB, Magic Mouse 2, Stainless Steel with Feet",
        //   // payStatus: 0, //支付状态
        //   freight: 10, //运费
        //   num: 1,
        //   price: 10000.33,
        //   icon: "../static/imac-white-1.png",
        //   amount: 30010.333, //总价
        //   skuTag: ["灰色", "32G"],
        //   // skusInfo: [
        //   //   {
        //   //     skuName: "颜色",
        //   //     skuValue: "灰色",
        //   //   },
        //   //   {
        //   //     skuName: "内存",
        //   //     skuValue: "32G",
        //   //   },
        //   // ],
        // },
        // {
        //   // isOpt: 0,
        //   spuId: 11,
        //   skuId: 101,
        //   orderId: "1586242977480760991",
        //   spuName:
        //     "Apple Mac Pro Desktop Computer, 3.5GHz 8-Core Intel Xeon W, 32GB Memory, 256GB SSD, Radeon Pro 580X 8GB, Magic Mouse 2, Stainless Steel with Feet",
        //   payStatus: 0, //支付状态
        //   freight: 20, //运费
        //   num: 2,
        //   price: "20000.55",
        //   icon: "../static/imac-white-1.png",
        //   amount: 50010.55, //总价
        //   skusInfo: ["灰色", "32G"],
        // },
        // {
        //   isOpt: 0,
        //   spuId: 12,
        //   skuId: 102,
        //   orderId: "1586242977480760991",
        //   spuName:
        //     "Apple Mac Pro Desktop Computer, 3.5GHz 8-Core Intel Xeon W, 32GB Memory, 256GB SSD, Radeon Pro 580X 8GB, Magic Mouse 2, Stainless Steel with Feet",
        //   payStatus: 0, //支付状态
        //   freight: 20, //运费
        //   num: 2,
        //   price: "30000.55",
        //   icon: "../static/imac-white-1.png",
        //   amount: 50010.55, //总价
        //   skusInfo: ["灰色", "32G"],
        // },
        // {
        //   isOpt: 0,
        //   spuId: 13,
        //   skuId: 103,
        //   orderId: "1586242977480760991",
        //   spuName:
        //     "Apple Mac Pro Desktop Computer, 3.5GHz 8-Core Intel Xeon W, 32GB Memory, 256GB SSD, Radeon Pro 580X 8GB, Magic Mouse 2, Stainless Steel with Feet",
        //   payStatus: 0, //支付状态
        //   freight: 20, //运费
        //   num: 2,
        //   price: "40000.55",
        //   icon: "../static/imac-white-1.png",
        //   amount: 50010.55, //总价
        //   skusInfo: ["灰色", "32G"],
        // },
      ],
    };
  },

  methods: {
    //全选
    checkAll() {
      this.banClick = true;
      let isAllOptFlag = null;
      if (
        this.opt.length == this.cardDetail.length &&
        this.opt.indexOf(-1) == -1
      ) {
        this.toggleAll();
        isAllOptFlag = false;
      } else {
        var num = new Array();
        for (let index = 0; index < this.cardDetail.length; index++) {
          num[index] = index;
        }
        this.opt = num;
        this.optAmount();

        isAllOptFlag = true;
      }

      let token = this.$cookie.get("shoptoken");
      if (token == null) {
        this.$router.push({
          path: "/login",
          query: { item: this.$route.path },
        });
      }
      //全选请求
      const _this = this;
      axios
        .get(this.$api + "card/updateAllCardOpt", {
          params: {
            token: token,
            isAllOpt: isAllOptFlag,
          },
        })
        .then(function (resp) {
          if (resp.data.code == 0) {
            _this.banClick = false;
          } else {
            _this.$router.go(0);
          }
        });
    },
    toggleAll() {
      this.opt = [];
      this.optAmount();
    },
    // 点击每个复选框
    optAmount(index) {
      // console.log("点击每个复选框：" + this.opt);
      // console.log(index);
      // console.log(this.cardDetail[0].isOpt);
      // console.log(this.cardDetail[1].isOpt);

      if (this.opt.length === 0) {
        this.cardAmount = 0;
        return;
      }

      this.cardAmount = 0;
      for (let index = 0; index < this.opt.length; index++) {
        if (this.opt[index] != -1) {
          this.cardAmount +=
            (this.cardDetail[this.opt[index]].num *
              this.cardDetail[this.opt[index]].price +
              this.cardDetail[this.opt[index]].freight) *
            100;
        }
      }
      // console.log(this.opt)

      let isShopToken = this.$cookie.get("shoptoken");
      if (isShopToken == null) {
        this.$router.push({
          path: "/login",
          query: { item: this.$route.path },
        });
      }

      //点击复选框修改状态码
      if (index != undefined) {
        this.banClick = true;
        //如果是点击步进器 调用的此方法，index为空
        if (this.cardDetail[index].isOpt == 0) {
          this.cardDetail[index].isOpt = 1;
        } else {
          this.cardDetail[index].isOpt = 0;
        }

        const _this = this;
        axios
          .get(this.$api + "card/updateCardIsOpt", {
            params: {
              token: isShopToken,
              skuId: _this.cardDetail[index].skuId,
              isOpt: _this.cardDetail[index].isOpt,
            },
          })
          .then(function (resp) {
            console.log("点击复选框的回调");
            console.log(resp);
            if (resp.data.code == 0) {
              _this.banClick = false;
            } else {
              _this.$router.go(0);
            }
          });
      }
    },
    onSubmit() {
      //找到选中的sku以及数量的集合
      // let optSkuNumList = [];
      // let optSkuObject = { skuId: null, num: null };
      // let newIndex = -1; //创建一个从0开始的索引，每次循环+1

      // for (let index = 0; index < this.opt.length; index++) {
      //   if (this.opt[index] != -1) {
      //     optSkuObject.skuId = this.cardDetail[this.opt[index]].skuId;
      //     optSkuObject.num = this.cardDetail[this.opt[index]].num;
      //     newIndex = newIndex + 1;
      //     optSkuNumList[newIndex] = optSkuObject;
      //   }
      // }

      // 传到详情页的数据
      // let json = JSON.stringify(optSkuNumList);
      // console.log("购物车页面json："+json)

      //获取当前页面详情固定数据，跳转后刷新页面会失效
      // let nIndex = -1;
      // let optSkusDetailList = [];
      // for (let index = 0; index < this.opt.length; index++) {
      //   nIndex = nIndex + 1;
      //   optSkusDetailList[nIndex] = this.cardDetail[this.opt[index]];
      //   // console.log("this.opt[]的值："+this.opt[index])
      //   // console.log("this.cardDetail[].isOpt的值："+this.cardDetail[index].isOpt)
      // }

      this.$router.push({
        path: "/orderDetail",
        // query: { item: optSkusDetailList },
      });
    },
    stepper(item) {
      console.log("步进器计数");
      console.log(item);
      this.stepperCount = item;
      this.optAmount();

      this.banClick = true;
      let isShopToken = this.$cookie.get("shoptoken");
      if (isShopToken == null) {
        this.$router.push({
          path: "/login",
          query: { item: this.$route.path },
        });
      }

      //步进器，等待 this.stepperOfCheckboxIndex = index; 完成赋值，再发送请求
      this.timer = setTimeout(() => {
        //设置延迟执行

        const _this = this;
        axios
          .get(this.$api + "card/updateCardSkuNum", {
            params: {
              token: isShopToken,
              skuId: _this.cardDetail[_this.stepperOfCheckboxIndex].skuId,
              skuNum: _this.stepperCount,
            },
          })
          .then(function (resp) {
            if (resp.data.code == 0) {
              _this.banClick = false;
            } else {
              _this.$router.go(0);
            }
          });
      }, 0.0000001);
    },
    goItem(spuId) {
      console.log(spuId);
      this.$router.push({ path: "/item", query: { spuId: spuId } });
    },

    stepperOfCheckbox(index) {
      console.log("步进器所在的复选框index");
      console.log(index);
      this.stepperOfCheckboxIndex = index;
    },

    deleteCard() {
      let token = this.$cookie.get("shoptoken");
      if (token == null) {
        this.$router.push({
          path: "/login",
          query: { item: this.$route.path },
        });
      }

      const _this = this;
      axios
        .get(this.$api + "card/deleteCard", {
          params: {
            token: token,
          },
        })
        .then(function (resp) {
          if (resp.data.code == 0) {
            axios
              .get(_this.$api + "card/list", {
                params: {
                  token: token,
                },
              })
              .then(function (resp) {
                _this.cardDetail = resp.data.data.cardDetail;
              });
          }
        });
    },
  },
};
</script>
<style scope>
.van-checkbox__label {
  width: 100%;
  color: rgb(255, 118, 182);
}
.m-item {
  border: rgb(115, 192, 243) solid 0.5rem;
  border-top: none;
  color: rgb(255, 108, 120);
  overflow: hidden;
}
.van-button {
  background: rosybrown;
  border: rosybrown;
}
.van-submit-bar__price {
  color: rosybrown;
}
.van-submit-bar__button {
  width: 4rem;
}
</style>
